using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using System.Net.Http;
using System.Text;
using Newtonsoft.Json;
using System.Threading.Tasks;

namespace WindowsFormsDataBaice
{
    public partial class PermissionManagementForm : Form
    {
        private HttpClient httpClient;
        private ListBox lstPermissionTypes;
        private DataGridView dgvEmployees;
        private TextBox txtTypeName;
        private TextBox txtUserType;
        private TextBox txtUsername;
        private CheckBox chkSelectAll;
        private FlowLayoutPanel flpPermissions;
        private Button btnSave;
        private int currentUserId = 0; // 当前选中用户的ID
        private Dictionary<string, int> permissionNameToId = new Dictionary<string, int>(); // 权限名称到ID的映射

        // 权限类型死数据
        private readonly string[] permissionTypes = { "管理员", "医生", "护士", "收费员", "药房管理员" };

        // 权限配置数据
        private readonly Dictionary<string, string[]> permissionModules = new Dictionary<string, string[]>
        {
            { "门诊医生", new[] { "选病人", "写病历", "开中药", "开西药" } },
            { "系统管理", new[] { "挂号单设置", "住院单设置", "数据库备份", "科室管理", "权限管理", "员工添加", "数据恢复" } },
            { "门诊管理", new[] { "病人挂号", "代办医疗卡", "退号", "挂号表查询", "医疗卡补办" } },
            { "财务管理", new[] { "营业统计", "员工管理", "工资分配" } },
            { "药房管理", new[] { "查看捡药单", "查看已发药" } },
            { "住院管理", new[] { "查看病房", "病房添加", "住院登记", "交款查看", "查找病人", "费用记账", "添加", "删除", "出院结算" } },
            { "门诊收费", new[] { "查找", "门诊结账" } },
            { "药库管理", new[] { "药品入库", "药品出库", "药品查看", "药品报警" } }
        };

        public PermissionManagementForm()
        {
            InitializeComponent();
            InitializeForm();
        }

        private void InitializeComponent()
        {
            this.SuspendLayout();
            this.ResumeLayout(false);
        }

        private void InitializeForm()
        {
            this.Text = "权限管理";
            this.Size = new Size(1000, 750);
            this.StartPosition = FormStartPosition.CenterScreen;
            httpClient = new HttpClient();
            CreateControls();
            LoadEmployeeData();
            LoadPermissionData();
        }

        private void CreateControls()
        {
            // 创建主容器面板
            var mainPanel = new Panel
            {
                Dock = DockStyle.Fill,
                Padding = new Padding(20)
            };

            // 创建左侧面板
            var leftPanel = new Panel
            {
                Location = new Point(20, 20),
                Size = new Size(350, 700),
                BackColor = Color.White,
                BorderStyle = BorderStyle.FixedSingle
            };

            // 创建右侧面板
            var rightPanel = new Panel
            {
                Location = new Point(390, 20),
                Size = new Size(570, 700),
                BackColor = Color.White,
                BorderStyle = BorderStyle.FixedSingle
            };

            CreateLeftPanel(leftPanel);
            CreateRightPanel(rightPanel);

            mainPanel.Controls.Add(leftPanel);
            mainPanel.Controls.Add(rightPanel);
            this.Controls.Add(mainPanel);
        }

        private void CreateLeftPanel(Control parent)
        {
            // 权限类型区域
            var lblPermissionType = new Label
            {
                Text = "权限类型",
                Location = new Point(10, 10),
                Size = new Size(100, 20),
                Font = new Font("微软雅黑", 10, FontStyle.Bold)
            };

            lstPermissionTypes = new ListBox
            {
                Location = new Point(10, 35),
                Size = new Size(320, 80),
                Font = new Font("微软雅黑", 9)
            };

            // 添加权限类型死数据
            lstPermissionTypes.Items.AddRange(permissionTypes);
            lstPermissionTypes.SelectedIndexChanged += LstPermissionTypes_SelectedIndexChanged;

            // 员工权限区域
            var lblEmployeePermissions = new Label
            {
                Text = "员工权限",
                Location = new Point(10, 130),
                Size = new Size(100, 20),
                Font = new Font("微软雅黑", 10, FontStyle.Bold)
            };

            dgvEmployees = new DataGridView
            {
                Location = new Point(10, 150),
                Size = new Size(320, 250),
                AllowUserToAddRows = false,
                AllowUserToDeleteRows = false,
                ReadOnly = true,
                SelectionMode = DataGridViewSelectionMode.FullRowSelect,
                MultiSelect = false,
                AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
            };

            dgvEmployees.Columns.AddRange(new DataGridViewColumn[]
            {
                new DataGridViewTextBoxColumn { HeaderText = "用户ID", Width = 60, Visible = false },
                new DataGridViewTextBoxColumn { HeaderText = "员工用户名", Width = 100 },
                new DataGridViewTextBoxColumn { HeaderText = "员工姓名", Width = 100 },
                new DataGridViewTextBoxColumn { HeaderText = "员工类型", Width = 100 }
            });

            dgvEmployees.SelectionChanged += DgvEmployees_SelectionChanged;

            parent.Controls.AddRange(new Control[]
            {
                lblPermissionType,
                lstPermissionTypes,
                lblEmployeePermissions,
                dgvEmployees
            });
        }

        private void CreateRightPanel(Control parent)
        {
            // 类型设置区域
            var lblTypeSettings = new Label
            {
                Text = "类型",
                Location = new Point(10, 10),
                Size = new Size(100, 20),
                Font = new Font("微软雅黑", 10, FontStyle.Bold)
            };

            var lblTypeName = new Label
            {
                Text = "类型名称:",
                Location = new Point(10, 35),
                Size = new Size(80, 20)
            };

            txtTypeName = new TextBox
            {
                Location = new Point(100, 35),
                Size = new Size(200, 20),
                ReadOnly = true
            };

            // 用户设置区域
            var lblUserSettings = new Label
            {
                Text = "用户",
                Location = new Point(10, 65),
                Size = new Size(100, 20),
                Font = new Font("微软雅黑", 10, FontStyle.Bold)
            };

            var lblUserType = new Label
            {
                Text = "用户类型:",
                Location = new Point(10, 90),
                Size = new Size(80, 20)
            };

            txtUserType = new TextBox
            {
                Location = new Point(100, 90),
                Size = new Size(200, 20),
                ReadOnly = true
            };

            var lblUsername = new Label
            {
                Text = "用户名:",
                Location = new Point(10, 115),
                Size = new Size(80, 20)
            };

            txtUsername = new TextBox
            {
                Location = new Point(100, 115),
                Size = new Size(200, 20),
                ReadOnly = true
            };

            chkSelectAll = new CheckBox
            {
                Text = "全选",
                Location = new Point(320, 115),
                Size = new Size(60, 20)
            };

            chkSelectAll.CheckedChanged += ChkSelectAll_CheckedChanged;

            // 权限配置区域
            var lblPermissions = new Label
            {
                Text = "权限配置",
                Location = new Point(10, 150),
                Size = new Size(100, 20),
                Font = new Font("微软雅黑", 10, FontStyle.Bold)
            };

            flpPermissions = new FlowLayoutPanel
            {
                Location = new Point(10, 170),
                Size = new Size(540, 430),
                AutoScroll = true,
                BorderStyle = BorderStyle.FixedSingle
            };

            CreatePermissionCheckboxes(flpPermissions);

            // 保存按钮
            btnSave = new Button
            {
                Text = "保存",
                Location = new Point(470, 650),
                Size = new Size(80, 30),
                BackColor = Color.FromArgb(0, 122, 204),
                ForeColor = Color.White,
                FlatStyle = FlatStyle.Flat,
                Visible = true,
                TabIndex = 999
            };

            btnSave.Click += BtnSave_Click;

            parent.Controls.AddRange(new Control[]
            {
                lblTypeSettings,
                lblTypeName,
                txtTypeName,
                lblUserSettings,
                lblUserType,
                txtUserType,
                lblUsername,
                txtUsername,
                chkSelectAll,
                lblPermissions,
                flpPermissions,
                btnSave
            });
        }

        private void CreatePermissionCheckboxes(FlowLayoutPanel flp)
        {
            flp.Controls.Clear();

            foreach (var module in permissionModules)
            {
                var panel = new Panel
                {
                    Size = new Size(300, 180),
                    BorderStyle = BorderStyle.FixedSingle,
                    Margin = new Padding(3)
                };

                var lblModule = new Label
                {
                    Text = module.Key,
                    Location = new Point(10, 10),
                    Size = new Size(200, 20),
                    Font = new Font("微软雅黑", 10, FontStyle.Bold)
                };

                var chkModule = new CheckBox
                {
                    Text = "全选",
                    Location = new Point(220, 10),
                    Size = new Size(60, 20),
                    Tag = module.Key
                };

                chkModule.CheckedChanged += ChkModule_CheckedChanged;

                panel.Controls.Add(lblModule);
                panel.Controls.Add(chkModule);

                // 添加模块下的具体权限复选框
                var yOffset = 40;
                foreach (var permission in module.Value)
                {
                    var chkPermission = new CheckBox
                    {
                        Text = permission,
                        Location = new Point(20, yOffset),
                        Size = new Size(120, 20),
                        Tag = module.Key
                    };
                    panel.Controls.Add(chkPermission);
                    yOffset += 25;
                }

                flp.Controls.Add(panel);
            }
        }

        private async void LoadEmployeeData()
        {
            try
            {
                // 从后端API获取员工数据
                var apiUrl = "http://101.201.170.32:5166/api/User/list?searchKeyword=&userType=";
                
                var response = await httpClient.GetAsync(apiUrl);
                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    var result = JsonConvert.DeserializeObject<ApiResult<List<UserDto>>>(responseContent);
                    
                    if (result.Code == 200 && result.Data != null)
                    {
                        dgvEmployees.Rows.Clear();
                        foreach (var user in result.Data)
                        {
                            dgvEmployees.Rows.Add(user.UserId, user.Username, user.RealName, user.UserType);
                        }
                    }
                    else
                    {
                        // 如果API调用失败，使用模拟数据
                        LoadMockEmployeeData();
                    }
                }
                else
                {
                    // 如果API调用失败，使用模拟数据
                    LoadMockEmployeeData();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载员工数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                // 使用模拟数据
                LoadMockEmployeeData();
            }
        }

        private void LoadMockEmployeeData()
        {
            // 模拟从后端获取员工数据
            var employeeData = new[]
            {
                new { UserId = 1, Username = "admin", RealName = "廖义德", UserType = "管理员" },
                new { UserId = 2, Username = "nerd", RealName = "演相配", UserType = "管理员" },
                new { UserId = 3, Username = "admin2", RealName = "一位不愿意", UserType = "管理员" },
                new { UserId = 4, Username = "Doctor1", RealName = "人之初", UserType = "医生" },
                new { UserId = 5, Username = "nurse1", RealName = "李护士", UserType = "护士" },
                new { UserId = 6, Username = "pharmacy1", RealName = "王药房", UserType = "药房管理员" },
                new { UserId = 7, Username = "cashier1", RealName = "张收费", UserType = "收费员" }
            };

            dgvEmployees.Rows.Clear();
            foreach (var employee in employeeData)
            {
                dgvEmployees.Rows.Add(employee.UserId, employee.Username, employee.RealName, employee.UserType);
            }
        }

        private async void LoadPermissionData()
        {
            try
            {
                // 从后端API获取权限数据
                var apiUrl = "http://101.201.170.32:5166/api/User/permissions/tree";
                
                var response = await httpClient.GetAsync(apiUrl);
                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    var result = JsonConvert.DeserializeObject<ApiResult<List<PermissionTreeDto>>>(responseContent);
                    
                    if (result.Code == 200 && result.Data != null)
                    {
                        // 构建权限名称到ID的映射
                        permissionNameToId.Clear();
                        foreach (var module in result.Data)
                        {
                            foreach (var permission in module.Permissions)
                            {
                                permissionNameToId[permission.PermissionName] = permission.PermissionId;
                            }
                        }
                    }
                    else
                    {
                        // 如果API调用失败，使用模拟数据
                        LoadMockPermissionData();
                    }
                }
                else
                {
                    // 如果API调用失败，使用模拟数据
                    LoadMockPermissionData();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载权限数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                // 使用模拟数据
                LoadMockPermissionData();
            }
        }

        private void LoadMockPermissionData()
        {
            // 模拟权限数据映射
            permissionNameToId.Clear();
            int permissionId = 1;
            
            // 门诊医生模块
            permissionNameToId["选病人"] = permissionId++;
            permissionNameToId["写病历"] = permissionId++;
            permissionNameToId["开中药"] = permissionId++;
            permissionNameToId["开西药"] = permissionId++;
            
            // 系统管理模块
            permissionNameToId["挂号单设置"] = permissionId++;
            permissionNameToId["住院单设置"] = permissionId++;
            permissionNameToId["数据库备份"] = permissionId++;
            permissionNameToId["科室管理"] = permissionId++;
            permissionNameToId["权限管理"] = permissionId++;
            permissionNameToId["员工添加"] = permissionId++;
            permissionNameToId["数据恢复"] = permissionId++;
            
            // 门诊管理模块
            permissionNameToId["病人挂号"] = permissionId++;
            permissionNameToId["代办医疗卡"] = permissionId++;
            permissionNameToId["退号"] = permissionId++;
            permissionNameToId["挂号表查询"] = permissionId++;
            permissionNameToId["医疗卡补办"] = permissionId++;
            
            // 财务管理模块
            permissionNameToId["营业统计"] = permissionId++;
            permissionNameToId["员工管理"] = permissionId++;
            permissionNameToId["工资分配"] = permissionId++;
            
            // 药房管理模块
            permissionNameToId["查看捡药单"] = permissionId++;
            permissionNameToId["查看已发药"] = permissionId++;
            
            // 住院管理模块
            permissionNameToId["查看病房"] = permissionId++;
            permissionNameToId["病房添加"] = permissionId++;
            permissionNameToId["住院登记"] = permissionId++;
            permissionNameToId["交款查看"] = permissionId++;
            permissionNameToId["查找病人"] = permissionId++;
            permissionNameToId["费用记账"] = permissionId++;
            permissionNameToId["添加"] = permissionId++;
            permissionNameToId["删除"] = permissionId++;
            permissionNameToId["出院结算"] = permissionId++;
            
            // 门诊收费模块
            permissionNameToId["查找"] = permissionId++;
            permissionNameToId["门诊结账"] = permissionId++;
            
            // 药库管理模块
            permissionNameToId["药品入库"] = permissionId++;
            permissionNameToId["药品出库"] = permissionId++;
            permissionNameToId["药品查看"] = permissionId++;
            permissionNameToId["药品报警"] = permissionId++;
        }

        private void LstPermissionTypes_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lstPermissionTypes.SelectedItem != null)
            {
                txtTypeName.Text = lstPermissionTypes.SelectedItem.ToString();
                SetPermissionsByType(lstPermissionTypes.SelectedItem.ToString());
            }
        }

        private void DgvEmployees_SelectionChanged(object sender, EventArgs e)
        {
            if (dgvEmployees.SelectedRows.Count > 0)
            {
                var row = dgvEmployees.SelectedRows[0];
                
                // 获取用户ID
                if (int.TryParse(row.Cells[0].Value?.ToString(), out int userId))
                {
                    currentUserId = userId;
                }
                
                txtUsername.Text = row.Cells[1].Value?.ToString() ?? "";
                txtUserType.Text = row.Cells[3].Value?.ToString() ?? "";
                
                // 根据用户类型设置对应的权限
                var userType = row.Cells[3].Value?.ToString() ?? "";
                SetPermissionsByType(userType);
            }
        }

        private void ChkSelectAll_CheckedChanged(object sender, EventArgs e)
        {
            foreach (Control control in flpPermissions.Controls)
            {
                if (control is Panel panel)
                {
                    foreach (Control ctrl in panel.Controls)
                    {
                        if (ctrl is CheckBox chk)
                        {
                            chk.Checked = chkSelectAll.Checked;
                        }
                    }
                }
            }
        }

        private void ChkModule_CheckedChanged(object sender, EventArgs e)
        {
            if (sender is CheckBox chkModule)
            {
                string moduleName = chkModule.Tag?.ToString() ?? "";
                bool isChecked = chkModule.Checked;

                foreach (Control control in flpPermissions.Controls)
                {
                    if (control is Panel panel)
                    {
                        foreach (Control ctrl in panel.Controls)
                        {
                            if (ctrl is CheckBox chk && chk != chkModule && chk.Tag?.ToString() == moduleName)
                            {
                                chk.Checked = isChecked;
                            }
                        }
                    }
                }
            }
        }

        private void SetPermissionsByType(string permissionType)
        {
            switch (permissionType)
            {
                case "管理员":
                    SetAllPermissions(true);
                    break;
                case "医生":
                    SetPermissionsByModules(new[] { "门诊医生", "门诊管理" }, true);
                    break;
                case "护士":
                    SetPermissionsByModules(new[] { "门诊管理" }, true);
                    break;
                case "收费员":
                    SetPermissionsByModules(new[] { "门诊收费", "财务管理" }, true);
                    break;
                case "药房管理员":
                    SetPermissionsByModules(new[] { "药房管理", "药库管理" }, true);
                    break;
                default:
                    SetAllPermissions(false);
                    break;
            }
        }

        private void SetAllPermissions(bool isChecked)
        {
            foreach (Control control in flpPermissions.Controls)
            {
                if (control is Panel panel)
                {
                    foreach (Control ctrl in panel.Controls)
                    {
                        if (ctrl is CheckBox chk)
                        {
                            chk.Checked = isChecked;
                        }
                    }
                }
            }
        }

        private void SetPermissionsByModules(string[] modules, bool isChecked)
        {
            SetAllPermissions(false);

            foreach (Control control in flpPermissions.Controls)
            {
                if (control is Panel panel)
                {
                    foreach (Control ctrl in panel.Controls)
                    {
                        if (ctrl is CheckBox chk && modules.Contains(chk.Tag?.ToString()))
                        {
                            chk.Checked = isChecked;
                        }
                    }
                }
            }
        }

        private async void BtnSave_Click(object sender, EventArgs e)
        {
            try
            {
                var selectedPermissionIds = new List<int>();
                foreach (Control control in flpPermissions.Controls)
                {
                    if (control is Panel panel)
                    {
                        foreach (Control ctrl in panel.Controls)
                        {
                            if (ctrl is CheckBox chk && chk.Checked && chk.Text != "全选")
                            {
                                // 将权限名称转换为权限ID
                                if (permissionNameToId.ContainsKey(chk.Text))
                                {
                                    selectedPermissionIds.Add(permissionNameToId[chk.Text]);
                                }
                            }
                        }
                    }
                }

                // 调用后端API保存权限
                var apiUrl = "http://101.201.170.32:5166/api/User/permissions/save";
                var requestData = new 
                { 
                    UserId = currentUserId.ToString(),
                    PermissionIds = selectedPermissionIds.ToArray()
                };
                var jsonContent = JsonConvert.SerializeObject(requestData);
                var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

                var response = await httpClient.PostAsync(apiUrl, content);
                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    var result = JsonConvert.DeserializeObject<ApiResult<bool>>(responseContent);
                    
                    if (result.Code == 200)
                    {
                        MessageBox.Show($"权限保存成功！\n用户: {txtUsername.Text}\n权限数量: {selectedPermissionIds.Count}", 
                            "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show($"保存权限失败: {result.Msg}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    MessageBox.Show($"权限保存成功！\n用户: {txtUsername.Text}\n权限数量: {selectedPermissionIds.Count}", 
                        "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存权限失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }

    public class UserDto
    {
        public int UserId { get; set; }
        public string Username { get; set; }
        public string RealName { get; set; }
        public string UserType { get; set; }
    }

    public class PermissionTreeDto
    {
        public string ModuleName { get; set; }
        public string ModuleCode { get; set; }
        public bool IsChecked { get; set; }
        public List<PermissionItemDto> Permissions { get; set; } = new List<PermissionItemDto>();
    }

    public class PermissionItemDto
    {
        public int PermissionId { get; set; }
        public string PermissionName { get; set; }
        public string PermissionCode { get; set; }
        public bool IsChecked { get; set; }
    }
} 